<?php
class StatisticsModel extends CI_Model{
	
	public function __construct(){
		parent::__construct();
	}
	
	public function statistics_count(){
		return $this->db->count_all("bills");
	}
	
	/*
	 * get list all bills from db:
	 */
	function fetch_statistics($limit, $start){
		$this->db->limit($limit, $start);
		$this->db->select('b._id as _id, user_id, u.first_name as first_name, u.last_name as last_name, bill_code, date, start_time, end_time, table_id, t.table_name as table_name, feedback, total_cost');
		$this->db->from('bills as b');
		$this->db->join('users as u', 'u._id = b.user_id');
		$this->db->join('tables as t', 't._id = b.table_id');
        
		//run select
		$query = $this -> db -> get();
 
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
	}
	
	public function get_bill_by_date($begin_date, $end_date){
		$begin = date($begin_date);
		$end = date($end_date);
		$this->db->select('b._id as _id, user_id, bill_code, date, start_time, end_time, table_id, feedback, total_cost');
		$this->db->from('bills as b');
		$this->db->where('date >=', $begin);
		$this->db->where('date <=', $end);
		
		$query = $this->db->get();
		
		if ($query->num_rows() > 0){
			return $query->result();
		}
		
		return false;
	}
	
	public function get_bill_description_by_date($begin_date, $end_date){
		$begin = date($begin_date);
		$end = date($end_date);
		$this->db->select('b._id as _id, bill_id, food_id, d.name as name, number, food_note, date, start_time, serve_time, cost, description, feedback');
		$this->db->from('bill_description as b');
		$this->db->join('dishes as d', 'd._id = b.food_id');
		$this->db->where('date >=', $begin);
		$this->db->where('date <=', $end);
		
		$query = $this->db->get();
		
		if ($query->num_rows() > 0){
			return $query->result();
		}
		
		return false;
	}
	
	public function bill_description_detail($bill_id){
		$this->db->select('d._id as _id, d.name as name, bd.cost as cost, bd.number as number, d.unit as unit, bd.start_time as start_time, bd.serve_time as serve_time, bd.feedback as feedback');
		$this->db->from('bill_description as bd');
		$this->db->join('dishes as d', 'bd.food_id = d._id');
		$this->db->where('bill_id', $bill_id);
		
		//run select
		$query = $this -> db -> get();
		
		if ($query->num_rows() > 0){
			$result = $query->result();
			return $result;
		}
		
		return false;
	}
}